package com.itheima.controller.backend.security;

import com.itheima.mapper.UserMapper;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SpringSecurityUserService implements UserDetailsService {
    //查找服务，实现查询数据库
    @Autowired
    private UserMapper userMapper;

    //根据用户名查询数据库中用户信息
    public User loadUserByUsername(String username) throws UsernameNotFoundException {



        // 从数据库中查询用户
        User user = userMapper.loadUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在！");
        }

        // 查询用户的角色
        List<Role> roles = userMapper.loadRolesByUserId(user.getId());
        // 把角色转换成数组
        String[] roleCodes = roles.stream()//
                .map(Role::getKeyword) // 如何选择? 选: 权限表示(唯一标识)  业务逻辑  一致性
                .collect(Collectors.toList())//
                .toArray(new String[0]);
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(roleCodes);
        // 设置用户的权限
        user.setAuthorities(authorityList);
        return user;
        /*// 设置用户的权限
        return null;*/ //原代码
    }
}
